package club.kynb.mall.application.flow.order;

import club.kynb.mall.application.context.MallUserContext;
import club.kynb.mall.application.context.OrderPreviewContext;
import club.kynb.mall.order.api.IShoppingCartService;
import club.kynb.mall.order.model.dto.ShoppingCartDTO;
import club.kynb.mall.product.api.IProductInfoService;
import club.kynb.mall.product.dto.ProductByParamDTO;
import club.kynb.mall.product.dto.ProductSkuDTO;
import club.kynb.mall.product.dto.ProductSpuDetailDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.common.web.exception.Errors;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.pizza.util.Checker;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kynb_club@163.com
 * @since 2021/7/5 9:02 下午
 */
@Slf4j
@Component
@AllArgsConstructor
public class BuildShoppingCartFilter implements Filter<OrderPreviewContext> {
    private final IShoppingCartService iShoppingCartService;
    private final IProductInfoService iProductInfoService;

    @Override
    public void doFilter(OrderPreviewContext orderPreviewContext, FilterInvoker<OrderPreviewContext> filterInvoker) {
        log.info("构建购物车过滤器 start");
        final MallUserContext mallUserContext = MallUserContext.get(true);
        final Long userId = mallUserContext.getUserDTO().getId();
        List<ShoppingCartDTO> checkedList = iShoppingCartService.getCheckedList(userId);
        //过滤下架商品
        List<Long> spuIdList = checkedList.stream().map(dto-> Long.valueOf(dto.getSpuId())).collect(Collectors.toList());
        final List<ProductSpuDetailDTO> productSpuList = iProductInfoService.listOnSaleByParam(new ProductByParamDTO().setIds(spuIdList));
        List<ProductSkuDTO> skuList = productSpuList.stream().flatMap(spuAndSkuDTO -> spuAndSkuDTO.getSkuList().stream()).collect(Collectors.toList());
        List<String> skuIds = skuList.stream().map(ProductSkuDTO::getId).collect(Collectors.toList());
        List<ShoppingCartDTO> filteredList = checkedList.stream().filter(shoppingCartDTO -> skuIds.contains(shoppingCartDTO.getSkuId())).collect(Collectors.toList());

        Checker.ifEmptyThrow(filteredList, () -> Errors.BIZ.exception("购物车没有选中商品，无法提交订单"));
        orderPreviewContext.setCheckedList(filteredList);
        log.info("构建购物车过滤器 end");
        filterInvoker.invoke(orderPreviewContext);
    }
}
